package ooday04;

public class PolymorphicDemo {
    public static void main(String[] args) {
        /*
        Dog o1 = new Dog();
        o1.age = 2;
        o1.name = "小黑";
        o1.color = "黑";
        o1.eat();
        o1.swim();
        o1.drink();
        o1.lookHome();
        Animal o2 = new Dog();
        o2.age = 2;
        o2.name = "小黑";
        o2.color = "黑";
        o1.eat();
        o1.drink();
        Swim o3 = new Dog();
        o3.swim();
         */


        //演示向上造型（多态）的第1点应用
        /*
        Master master = new Master();
        Dog dog = new Dog("小黑", 2, "黑");
        Chick chick = new Chick("小白", 2, "白");
        Fish fish = new Fish("小金", 2, "金");
        master.feed(dog);//在传参的同时系统自动给做了向上造型
        master.feed(chick);
        master.feed(fish);
         */


        //演示向上造型（多态）的第2点应用t

        Animal[] animals = new Animal[5];
        animals[0] = new Dog("小黑", 2, "黑");
        animals[1] = new Dog("小白", 2, "白");
        animals[2] = new Fish("小金", 2, "金");
        animals[3] = new Fish("小花", 2, "花");
        animals[4] = new Chick("小红", 2, "红");
        for (int i = 0; i < animals.length; i++) {//遍历所有动物
            System.out.println(animals[i].name);
            animals[i].eat();//所有动物吃饭
            animals[i].drink();//所有动物喝水
            if(animals[i] instanceof Dog){
                Dog dog=(Dog) animals[i];
                dog.lookHome();
            }
            if(animals[i] instanceof Chick){
                Chick chick=(Chick) animals[i];
                chick.layEggs();
            }
            if(animals[i] instanceof Swim){
                Swim swim=(Swim) animals[i];
                swim.swim();
            }
        }


        //演示强转成功的条件
        /*
        Animal o = new Dog("小黑", 2, "黑");//向上造型
        Dog g = (Dog)o;//引用o所指向的对象，就是Dog类型
        Swim s =(Swim)o;//引用o所指向的对象，实现了Swim接口
        //Fish f = (Fish)o;//运行时会发生异常

        System.out.println(o instanceof Dog);
        System.out.println(o instanceof Fish);
        System.out.println(o instanceof Chick);
        if(o instanceof Fish){
            Fish f = (Fish)o;
        }else {
            System.out.println("o不是Fish类型");
        }
         */
    }
}
